import chen.User2;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("Username");
        String password = request.getParameter("Password");

        int flag = 1;
        FileInputStream file = null;
        BufferedReader in = null;

        try {
            file = new FileInputStream("src/main/User.txt");
            in = new BufferedReader(new InputStreamReader(file));
            String usermessage = null;
            Jsonb jsonb = JsonbBuilder.create();
            while ((usermessage = in.readLine()) != null) {
                User2 userDTO = jsonb.fromJson(usermessage, User2.class);
                if(userDTO.getUsername().equals(username) && userDTO.getPassword().equals(password))
                {
                    flag = 0;
                    HttpSession session = request.getSession(true);
                    Map<String,String> hashmap = new HashMap<String,String>();
                    hashmap.put("username",userDTO.getUsername());
                    hashmap.put("password",userDTO.getPassword());
                    hashmap.put("email",userDTO.getEmail());
                    hashmap.put("sno",userDTO.getSno());
                    hashmap.put("img",userDTO.getImg());
                    hashmap.put("name",userDTO.getName());
                    //HttpSession session = request.getSession(true);
                    session.setAttribute("usermessage", hashmap);
                    session.setAttribute("token", "not null");
                    file.close();
                    in.close();
                    String str2 = hashmap.toString();
                    System.out.println(str2);
                    System.out.println(userDTO.getName());
                    break;
                }
            }
        } catch (IOException e) {
            response.sendRedirect("/error.html");
        }

        if(flag == 0) {
            response.sendRedirect("/index.jsp");
        }
        else {
            response.sendRedirect("/error.html");

        }

    }
}
